package ca.clarity.hms.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import ca.clarity.hms.provider.HmsVillage;
import ca.clarity.hms.rest.HmsVillageRest;
import ca.clarity.hms.util.NetworkChecker;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;

/**
 * village 선택 화면 activity class 이다.
 *
 * @author johnkim
 */
public class HmsVillageActivity extends Activity {

    public static String TAG = HmsVillageActivity.class.getSimpleName();

    // Clinic.
    Spinner clinicSpinner;

    // Village.
    Spinner villageSpinner;

    // 지역 선택 버튼.
    Button villageConfirmButton;

    // clinic 목록을 가져 온다.
    private static final int THREAD_SELECT_CLINIC_LIST = 101;

    // village 목록을 가져 온다.
    private static final int THREAD_SELECT_VILLAGE_LIST = 102;

    HmsVillageRest hmsVillageRest = new HmsVillageRest();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hms_village);

        // 네트워크 상태를 확인한다.
        if (NetworkChecker.getInstance().isNetworkConnected(getApplicationContext())) {

            Log.d(TAG, "네트워크가 활성화 상태입니다.");
        }


//        HmsVillage hmsVillage = new HmsVillage();
//        try {
//			hmsVillageRest.getVillageList(hmsVillage);
//		} catch (JSONException e1) {
//			// TODO Auto-generated catch block
//			e1.printStackTrace();
//		} catch (IOException e1) {
//			// TODO Auto-generated catch block
//			e1.printStackTrace();
//		}

        /**
         * Clinic
         */
        String clinicsStr = "{\"d\": {\n" +
                "    \"result\": \"success\",\n" +
                "    \"data\": [\n" +
                "        {\n" +
                "            \"Id\": 1,\n" +
                "            \"Name\": \"New York Test Practice\"\n" +
                "        },\n" +
                "        {\n" +
                "            \"Id\": 5,\n" +
                "            \"Name\": \"Geta Eye Hospital \"\n" +
                "        },\n" +
                "        {\n" +
                "            \"Id\": 6,\n" +
                "            \"Name\": \"Shri Sadguru Seva Sangh Trust, Chitrakoot\"\n" +
                "        },\n" +
                "        {\n" +
                "            \"Id\": 7,\n" +
                "            \"Name\": \"Ayo Bello Memorial Eye Center, ILORIN\"\n" +
                "        },\n" +
                "        {\n" +
                "            \"Id\": 8,\n" +
                "            \"Name\": \"Baptist Eye Hospital Lunsar\"\n" +
                "        },\n" +
                "        {\n" +
                "            \"Id\": 13,\n" +
                "            \"Name\": \"Dr. Salins Eye Hospital (Velemegna Good News Society), Golekhana, Bidar-585401, Karnataka India\"\n" +
                "        },\n" +
                "        {\n" +
                "            \"Id\": 14,\n" +
                "            \"Name\": \"Shenyang He Eye Hospital\"\n" +
                "        },\n" +
                "        {\n" +
                "            \"Id\": 15,\n" +
                "            \"Name\": \"Venu Eye Institute & Research Centre\"\n" +
                "        },\n" +
                "        {\n" +
                "            \"Id\": 16,\n" +
                "            \"Name\": \"Sri Sankaradeva Nethralaya, Guwahati – India \"\n" +
                "        },\n" +
                "        {\n" +
                "            \"Id\": 17,\n" +
                "            \"Name\": \"Centre Ophtalmologique Jean Paul II Lome\"\n" +
                "        },\n" +
                "        {\n" +
                "            \"Id\": 18,\n" +
                "            \"Name\": \"Lions eye Institute and hospital, dhaka\"\n" +
                "        },\n" +
                "        {\n" +
                "            \"Id\": 19,\n" +
                "            \"Name\": \"HCMC Eye Hospital \"\n" +
                "        },\n" +
                "        {\n" +
                "            \"Id\": 20,\n" +
                "            \"Name\": \"HelpAge\"\n" +
                "        },\n" +
                "        {\n" +
                "            \"Id\": 21,\n" +
                "            \"Name\": \"Sankara Eye Hospital \"\n" +
                "        },\n" +
                "        {\n" +
                "            \"Id\": 22,\n" +
                "            \"Name\": \"Little Flower Hospital \"\n" +
                "        },\n" +
                "        {\n" +
                "            \"Id\": 23,\n" +
                "            \"Name\": \"Lokeswarananda Eye Foundation\"\n" +
                "        },\n" +
                "        {\n" +
                "            \"Id\": 24,\n" +
                "            \"Name\": \"Smt. Sharda Jhatakia Hospital \"\n" +
                "        },\n" +
                "        {\n" +
                "            \"Id\": 25,\n" +
                "            \"Name\": \"Uska Kiran Charitable Trust\"\n" +
                "        },\n" +
                "        {\n" +
                "            \"Id\": 26,\n" +
                "            \"Name\": \"Sri Chaitanya Seva Trust- Bhakti Vedanta Hospital\"\n" +
                "        }\n" +
                "    ]\n" +
                "}}";

        // Clinic 목록.
        clinicSpinner = (Spinner) findViewById(R.id.clinicSpinner);

        ArrayList<String> outputClinicList = new ArrayList<String>();
        try {
            JSONObject jsonObject = new JSONObject(clinicsStr);

            JSONArray clinics = jsonObject.getJSONObject("d").getJSONArray("data");

            for (int i = 0; i < clinics.length(); i++) {
                JSONObject clinic = clinics.getJSONObject(i);
                outputClinicList.add(clinic.getString("Name"));
            }

            ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, outputClinicList);
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            clinicSpinner.setAdapter(adapter);

            // 선택 했을때.
            clinicSpinner.setOnItemSelectedListener(new ClinicSelectedListener());

        } catch (JSONException e) {
            e.printStackTrace();
        }

        // village 목록을 가져 온다.
        mHandler.sendMessage(mHandler.obtainMessage(THREAD_SELECT_VILLAGE_LIST));
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.hms_village, menu);
        return true;
    }


    public class ClinicSelectedListener implements AdapterView.OnItemSelectedListener {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

            String selectedItem = parent.getItemAtPosition(position).toString();

            Log.d("SelectedItem", selectedItem);

            if (selectedItem.trim().equals("Geta Eye Hospital")) {

                /**
                 * Village
                 */
                String villagesStr = "{\"d\": {\n" +
                        "    \"result\": \"success\",\n" +
                        "    \"data\": [\n" +
                        "        {\n" +
                        "            \"Id\": 1,\n" +
                        "            \"Name\": \"New York Test\",\n" +
                        "            \"ClinicId\": 1\n" +
                        "        },\n" +
                        "        {\n" +
                        "            \"Id\": 2,\n" +
                        "            \"Name\": \"India Test\",\n" +
                        "            \"ClinicId\": 6\n" +
                        "        },\n" +
                        "        {\n" +
                        "            \"Id\": 3,\n" +
                        "            \"Name\": \"New York\",\n" +
                        "            \"ClinicId\": 1\n" +
                        "        },\n" +
                        "        {\n" +
                        "            \"Id\": 4,\n" +
                        "            \"Name\": \"Seoul\",\n" +
                        "            \"ClinicId\": 1\n" +
                        "        },\n" +
                        "        {\n" +
                        "            \"Id\": 27,\n" +
                        "            \"Name\": \"Polygon Test\",\n" +
                        "            \"ClinicId\": 1\n" +
                        "        },\n" +
                        "        {\n" +
                        "            \"Id\": 28,\n" +
                        "            \"Name\": \"Polygon\",\n" +
                        "            \"ClinicId\": 1\n" +
                        "        },\n" +
                        "        {\n" +
                        "            \"Id\": 29,\n" +
                        "            \"Name\": \"B Test\",\n" +
                        "            \"ClinicId\": 6\n" +
                        "        },\n" +
                        "        {\n" +
                        "            \"Id\": 30,\n" +
                        "            \"Name\": \"B Test\",\n" +
                        "            \"ClinicId\": 6\n" +
                        "        },\n" +
                        "        {\n" +
                        "            \"Id\": 31,\n" +
                        "            \"Name\": \"B Test\",\n" +
                        "            \"ClinicId\": 6\n" +
                        "        },\n" +
                        "        {\n" +
                        "            \"Id\": 32,\n" +
                        "            \"Name\": \"Calgary FootHill\",\n" +
                        "            \"ClinicId\": 1\n" +
                        "        }\n" +
                        "    ]\n" +
                        "}}";

                // 지역 목록.
                villageSpinner = (Spinner) findViewById(R.id.villageSpinner);

                ArrayList<String> outputVillageList = new ArrayList<String>();
                try {
                    JSONObject jsonObject = new JSONObject(villagesStr);

                    JSONArray villages = jsonObject.getJSONObject("d").getJSONArray("data");

                    for (int i = 0; i < villages.length(); i++) {
                        JSONObject village = villages.getJSONObject(i);
                        outputVillageList.add(village.getString("Name"));
                    }

                    ArrayAdapter<String> adapter = new ArrayAdapter<String>(HmsVillageActivity.this, android.R.layout.simple_spinner_dropdown_item, outputVillageList);
                    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                    villageSpinner.setAdapter(adapter);


                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }


            // 지역 선택 버튼을 정의 한다.
            villageConfirmButton = (Button) findViewById(R.id.villageConfirmButton);
            villageConfirmButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // 지역을 선택한 뒤 선택버튼을 터치하면 메인 화면을 출력 한다.
                    Intent i = new Intent(HmsVillageActivity.this, HmsCvListActivity.class);
                    startActivity(i);
                }
            });
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    }

    /**
     * Handler 를 정의한다.
     * 모든 Thread 를 등록해 놓고 필요할때 호출한다.
     */
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                // 로그인을 한다.
                case THREAD_SELECT_CLINIC_LIST:
                    selectClinicList();
                    break;
                case THREAD_SELECT_VILLAGE_LIST:
                    selectVillageList();
                    break;
            }
        }
    };

    /**
     * clinic 목록을 가져 온다.
     */
    public void selectClinicList() {

    }

    /**
     * village 목록을 가져 온다.
     */
    public void selectVillageList() {
        try {
            hmsVillageRest.getVillageList();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
